import { action } from 'mobx'
import * as data from '../mock-data'

export class Actions {
  constructor(store) {
    this.store = store
  }

  @action.bound
  login({ token, userId }) {
    this.store.authentication.token = token
    this.store.authentication.userId = userId
  }

  @action.bound
  logout() {
    this.store.authentication.token = undefined
    this.store.authentication.userId = undefined
  }

  @action.bound
  addToCart(item, amount) {
    const { cart } = this.store
    const t = cart.find(t => t.item.id === item.id)
    if (t) {
      const nt = { ...t, amount: t.amount + 1 }
      this.store.cart = [nt, ...cart.filter(tt => tt !== t)]
    } else {
      this.store.cart = [{ item, amount }, ...cart]
    }
  }

  @action.bound
  setCartItemAmount(item, amount) {
    this.store.cart = this.store.cart.map(
      t => (t.item.id === item.id ? { ...t, amount } : t),
    )
  }

  @action.bound
  clearCart() {
    this.store.cart = []
  }
}
